<template>
	<view class="page-fade-in" :style="{opacity: pageOpc}">
		<template v-if="pageOpc">
			<view class="container">
				<view class="modle-title">活动设置</view>
				<view class="modle-info-box">
					<view class="info-item flexWrapNo">
						<view>活动名称：</view>
						<input placeholder="请输入活动名称,最多15个字" 
							maxlength="15"
							placeholder-class="placeholderclass" 
							v-model="form.activityName" 
							@paste="onPaste"
						/>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>活动有效期：</view>
							<picker @change="bindValidChange" :value="validIndex" :range="validArray" range-key="label">
								<view class="uni-input">{{validArray[validIndex].label}}</view>
							</picker>
						</view>
						<text class="icon-more"></text>
					</view>
					<block v-if="validIndex==1">
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>开始时间：</view>
								<picker mode="date" :data-index='0' :value="form.termStart" @change="bindDateChange" :start="currentDate">
									<view class="select-input" v-if="form.termStart">{{form.termStart}}</view>
									<view class="select-input" v-else>请选择开始时间</view>
								</picker>
							</view>
							<text class="icon-more"></text>
						</view>
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>结束时间：</view>
								<picker mode="date" :data-index='1' :value="form.termEnd" @change="bindDateChange" :start="form.termStart">
									<view class="select-input" v-if="form.termEnd">{{form.termEnd}}</view>
									<view class="select-input" v-else>请选择结束时间</view>
								</picker>
							</view>
							<text class="icon-more"></text>
						</view>
					</block>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>语音播报：</view>
							<switch color="#00E165" style="transform:scale(0.7)" :checked="form.broadcast" @change="switchChange"/>
						</view>
					</view>	
				</view>
				
				<view class="modle-title">活动条件</view>
				<view class="modle-info-box">
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">适用桌台：</view>
							<view class="select-input" @tap="handleMultiple">
							    {{shopValue || '请选择'}}
							</view>
						</view>
						<text class="icon-more"></text>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>订单实付金额：</view>
							<view style="margin-right: 28rpx;">满</view>
							<input placeholder="请输入0或正整数,0表示不限制" 
								placeholder-class="placeholderclass" 
								v-model="form.orderActualPay" type="number" 
								@input="handlePayInput"
							/>
						</view>
						<text>元</text>
					</view>
					<view class="remaks-box">
						充值抵扣、团购以及微信实付金额达到该金额及以上参与活动
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">订单结束时间段：</view>
							<picker @change="timeLimitChange" :value="timeLimitIndex" :range="timeLimitArray" range-key="label">
								<view class="uni-input">{{timeLimitArray[timeLimitIndex].label}}</view>
							</picker>
						</view>
						<text class="icon-more"></text>
					</view>
					<view class="info-item flexWrap" v-if="timeLimitIndex!=0">
						<view class="flexWrapNo" style="flex: 1;">
							<view class="item-title">时间段：</view>
							<view class="flexWrap">
								<picker mode="time" :value="useTimeStart" start="00:00" end="24:00" :data-index='0'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="useTimeStart">{{useTimeStart}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
								<text class="small">至</text>
								<picker mode="time" :value="useTimeEnd" :start="useTimeStart" end="24:00" :data-index='1'
									:data-arrIndex="index" @change="bindTimeChange" style="flex: none;">
									<view class="select-input" v-if="useTimeEnd">{{useTimeEnd}}</view>
									<view class="select-input" v-else>请选择时间</view>
								</picker>
							</view>
						</view>
					</view>
					<view class="remaks-box">
						可指定订单结束时间在时间段内参与活动或指定时间段内不参与活动
					</view>
				</view>
				<multiple-picker
				    :show="selectMultipleShow" 
				    :columns="selectMultipleColumns" 
				    :defaultIndex="shopIndex" 
				    @confirm="confirmMultiple" 
				    @cancel="selectMultipleShow = false"
				></multiple-picker>
				
				<view class="modle-title">返券/门店卡余额</view>
				<view class="modle-info-box">
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>返券/卡：</view>
							<radio-group  class="flexWrap radio-group" @change="couponsCardChange">
							    <label>
									<radio :value="1" :checked="form.couponsCard==1" style="transform: scale(0.7);"/>随机立减券
							    </label>
								<label>
									<radio :value="2" :checked="form.couponsCard==2" style="transform: scale(0.7);"/>门店卡余额
								</label>
							</radio-group>
						</view>
					</view>
					<view class="info-item flexWrap" v-if="form.couponsCard==1">
						<view class="flexWrapNo" style="flex: 1;">
							<view>立减券名称：</view>
							<input placeholder="请输入立减券名称,最多15个字" 
								maxlength="15" 
								placeholder-class="placeholderclass" 
								v-model="form.couponsName" 
								@paste="onPaste"
							/>
						</view>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>金额上限：</view>
							<input placeholder="请输入正整数" 
								placeholder-class="placeholderclass" 
								v-model="form.upperAmount" type="number" data-type="upperAmount" 
								@input="handleInput"
							/>
						</view>
						<text>元</text>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>金额下限：</view>
							<input placeholder="请输入正整数" 
								placeholder-class="placeholderclass" 
								v-model="form.lowerAmount" type="number" data-type="lowerAmount" 
								@input="handleInput"
							/>
						</view>
						<text>元</text>
					</view>
					<view class="info-item flexWrap" v-if="form.couponsCard==1">
						<view class="flexWrapNo" style="flex: 1;">
							<view>有效时间：</view>
							<picker @change="ticketPickerChange" :value="ticketValidIndex" :range="ticketValidArray" range-key="label">
								<view class="uni-input">{{ticketValidArray[ticketValidIndex].label}}</view>
							</picker>
						</view>
						<text class="icon-more"></text>
					</view>
					<block v-if="form.couponsCard==1&&ticketValidIndex==1">
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>开始时间：</view>
								<picker mode="date" :data-index='0' :value="ticketStartTime" @change="ticketDateChange" :start="currentDate">
									<view class="select-input" v-if="ticketStartTime">{{ticketStartTime}}</view>
									<view class="select-input" v-else>请选择开始时间</view>
								</picker>
							</view>
							<text class="icon-more"></text>
						</view>
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>结束时间：</view>
								<picker mode="date" :data-index='1' :value="ticketEndTime" @change="ticketDateChange" :start="ticketStarTime">
									<view class="select-input" v-if="ticketEndTime">{{ticketEndTime}}</view>
									<view class="select-input" v-else>请选择结束时间</view>
								</picker>
							</view>
							<text class="icon-more"></text>
						</view>
					</block>
					<view class="info-item flexWrap" v-if="form.couponsCard==1&&ticketValidIndex==2">
						<view class="flexWrapNo" style="flex: 1;">
							<view>有效天数：</view>
							<input placeholder="请输入天数" 
								placeholder-class="placeholderclass" 
								v-model="form.couponsTermTime" type="number" 
								maxlength="3" data-type="day" 
								@input="handleInput"
							/>
						</view>
						<text>天</text>
					</view>
					<view class="info-item flexWrap">
						<view class="flexWrapNo" style="flex: 1;">
							<view>发放方式：</view>
							<radio-group class="flexWrap radio-group" @change="grantTypeChange">
							    <label>
									<radio :value="1" :checked="form.grantType==1" style="transform: scale(0.7);"/>订单结束立返
							    </label>
								<label>
									<radio :value="2" :checked="form.grantType==2" style="transform: scale(0.7);"/>好友助力
								</label>
							</radio-group>
						</view>
					</view>
					<block v-if="form.grantType==2">
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>助力有效期：</view>
								<input placeholder="请输入正整数" 
									placeholder-class="placeholderclass" 
									v-model="form.assistTime" type="number" 
									maxlength="5" data-type="assistTime" 
									@input="handleInput"
								/>
							</view>
							<text>小时</text>
						</view>
						<view class="remaks-box">助力有效时长最多24小时</view>
						<view class="info-item flexWrap" >
							<view class="flexWrapNo" style="flex: 1;">
								<view>助力好友数：</view>
								<input placeholder="请输入正整数" 
									placeholder-class="placeholderclass" 
									v-model="form.assistNum" type="number" data-type="assistNum" 
									@input="handleInput"
								/>
							</view>
							<text>人</text>
						</view>
						<view class="remaks-box">助力好友最多5人</view>
						<view class="info-item flexWrap">
							<view class="flexWrapNo" style="flex: 1;">
								<view>助力成功获得人：</view>
								<radio-group class="flexWrap radio-group" @change="getTicket">
								    <label>
										<radio :value="1" :checked="form.assistSuccessType==1" style="transform: scale(0.7);"/>每人可获得
								    </label>
									<label>
										<radio :value="2" :checked="form.assistSuccessType==2" style="transform: scale(0.7);"/>仅发起人获得
									</label>
								</radio-group>
							</view>
						</view>
					</block>
				</view>
				<view class="submit-btn" @tap="submit">提交保存</view>	
			</view>
		</template>
	</view>
</template>

<script>
	export default{
		data(){
			const currentDate = this.getDate({
				format: true
			})
			return{
				pageOpc:0,
				form:{
					activityName:'',
					termType:1,  //  1：永久有效  2：自定义有效期
					termStart:'',  // 活动有效开始时间
					termEnd:'',  // 活动有效结束时间
					broadcast:true,  // 是否语音播报：true false
					tableType:'', // 桌台类型
					orderActualPay:'',  // 订单实付满多少可用
					useTimeType:1,  //订单使用时间段类型： 1不限  2指定时间参与  3指定时间不参与
					useTimeStart:'', //使用时间段开始
					useTimeEnd:'',  //使用时间段结束
					couponsCard:1, // 1券 2卡
					couponsName:'', // 立减券名称
					upperAmount:'',  // 金额上线
					lowerAmount:'',  // 金额下线
					couponsTermType:1, // 立减券有效时间类型  1永久 2指定日期  3指定天数
					couponsTermTime:'', // 立减券时间
					grantType:1, // 发放方式： 1订单结束立返  2好友助力
					assistTime:'',  // 助力有效期
					assistNum:'', // 助力好友数
					assistSuccessType:1, //1每人可获得 2仅发起人获得
				},
				useTimeStart:'', // 时间段开始时间
				useTimeEnd:'', // 时间段结束时间
				ticketStartTime:'',
				ticketEndTime:'',
				validArray: [
					{label:'永久有效',value:1},
					{label:'自定义有效期',value:2}
				],
				validIndex:0,
				currentDate:currentDate,
				
				selectMultipleShow:false,
				selectMultipleColumns:[
					// {label:'正式黑八',value:1},
				],
				shopValue: '',
				shopIndex: [],
				
				timeLimitArray:[
					{label:'不限时间段',value:1},
					{label:'指定时间段参与',value:2},
					{label:'指定时间段不参与',value:3}
				],
				timeLimitIndex:0,

				ticketValidArray: [
					{label:'永久有效',value:1},
					{label:'指定日期',value:2},
					{label:'指定天数',value:3}
				],
				ticketValidIndex:0,
				activityId:'', // 活动id
			}
		},
		
		onReady() {
			setTimeout(() => {
				this.pageOpc = 1
			}, 100)
		},
		onLoad(options) {
			this.activityId=options.id
			this.getTable()
			// if(this.activityId){
			// 	this.getDetail()
			// }
		},
		
		methods:{
			// 获取日期
			getDate(type) {
				const date = new Date();
				date.setDate(date.getDate());
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			
			// 获取桌台信息
			getTable(){
				this.$request.get(this.$api.getTableType, {
					isJava:true,
					storeId:uni.getStorageSync('store_id'),
				}).then(res => {
					if(res.code==200){
						console.log(res.data)
						let data=res.data
						data.forEach(item=>{
							this.selectMultipleColumns.push({
								label:item.value,
								value:item.key
							})
						})
						if(!this.activityId){
							let temp = []
							this.selectMultipleColumns.forEach(item=>{
								temp.push(item.label)
								this.shopIndex.push(item.value)
							})
							this.shopValue = temp.toString()
						}else{
							// 获取详情
							this.getDetail()
						}
					}
				})
			},
			
			// 获取获取详情
			getDetail(){
				this.$request.get(this.$api.returnActivityDetail, {
					isJava:true,
					id:this.activityId,
				}).then(res => {
					if(res.code==200){
						this.form=res.data
						this.shopIndex=this.convertStringToArray(this.form.tableType)
						let choose=this.getAbsentValues(this.selectMultipleColumns,this.shopIndex)
						let temp = []
						choose.forEach(item=>{
							temp.push(item.label)
						})
						this.shopValue = temp.toString()
						
						this.useTimeStart=this.form.useTimeStart?this.splitBySecondOccurrence(this.form.useTimeStart,":")[0]:''
						this.useTimeEnd=this.form.useTimeEnd?this.splitBySecondOccurrence(this.form.useTimeEnd,":")[0]:''
						
						this.validIndex=this.validArray.findIndex(item => item.value == this.form.termType)
						this.timeLimitIndex=this.timeLimitArray.findIndex(item => item.value == this.form.useTimeType)
						this.ticketValidIndex=this.ticketValidArray.findIndex(item => item.value == this.form.couponsTermType)
						if(this.ticketValidIndex==1&&this.form.couponsTermTime){
							this.ticketStartTime=this.form.couponsTermTime.split('~')[0]
							this.ticketEndTime=this.form.couponsTermTime.split('~')[1]
						}
					}
				})
			},
			
			// 过滤出选中的数据
			getAbsentValues(arr1, arr2){
			    let res = [];
			    res = arr1.filter(item => {
			        return arr2.find(el => {
			            return item.value == el
			       });
			    });
			    return res
			},
			
			convertStringToArray(commaSeparatedString) {
				if(commaSeparatedString){
					// 使用split函数以逗号为分隔符将字符串拆分为数组
					let numberArray = commaSeparatedString.split(',');
					// 使用map函数将字符串数组中的每个元素转换为数字
					numberArray = numberArray.map(Number);
					return numberArray;
				}else{
					return []
				}
			},
			
			// 第二个出现的特定分隔符处分割开
			splitBySecondOccurrence(str, delimiter) {
				const index = str.indexOf(delimiter);
				if (index === -1) {
					return [str]; // 如果没有找到分隔符，返回原字符串作为单个元素的数组
				}
				const secondIndex = str.indexOf(delimiter, index + 1);
				if (secondIndex === -1) {
					return [str]; // 如果只有一个分隔符，返回原字符串作为单个元素的数组
				}
				// 分割字符串
				return [
					str.slice(0, secondIndex), // 第一部分，从开始到第二个分隔符之前
					str.slice(secondIndex + delimiter.length), // 第二部分，从第二个分隔符之后开始
				];
			},
			
			onPaste(event) {
				// 处理粘贴时的内容限制
			    const clipboardData = event.clipboardData || window.clipboardData;
			    const pastedText = clipboardData.getData('text');
			
			    // 允许最多粘贴的字符
			    const maxLength = 15;
			    const remainingText = pastedText.slice(0, maxLength+1);
			
			    // 阻止默认粘贴行为并手动将处理后的文本设置到输入框
			    event.preventDefault();
			    // 这里需要使用$nextTick确保输入框的值被更新
			    this.$nextTick(() => {
			      event.target.value = remainingText;
			    });
			},
			
			// 订单实付金额输入限制（只能输入0或正整数）
			handlePayInput(event){
				let value = event.target.value;
				// 允许输入开头是0，但不允许输入多个0
				if (value.charAt(0) === '0' && value.length > 1) {
				  value = value.substring(1);
				}
				// 保证输入的是大于等于0的整数
				value = value.replace(/[^0-9]/g, '');
				//前两位不能是0加数字      
				// value = value.replace(/^0\d[0-9]*/g,'');
				this.$nextTick(()=>{
					this.form.orderActualPay = value;
				})
			},
			
			bindValidChange(e){
				this.validIndex = e.detail.value
				this.form.termType=this.validArray[this.validIndex].value
				console.log("this.form.termType")
			},
			
			bindDateChange(e){
				let index = e.currentTarget.dataset.index
				if (index == 0) {
					this.form.termStart = e.target.value
				} else {
					this.form.termEnd = e.target.value
				}
			},
			
			switchChange(e){
				this.form.broadcast=e.detail.value
			},
			
			handleMultiple(){
				this.selectMultipleShow = true
			},
			
			// 桌台选择确定
			confirmMultiple(e){
				let temp = [];
				e.selected.forEach(item => {
				    temp.push(item.label)
				})
				this.shopValue = temp.toString()
				this.shopIndex = e.value
				this.selectMultipleShow = false
			},
			
			timeLimitChange(e){
				this.timeLimitIndex = e.detail.value
				this.form.useTimeType=this.timeLimitArray[this.timeLimitIndex].value
			},
			
			// 选择时间
			bindTimeChange(e) {
				let index=e.target.dataset.index
				if(index==0){
					this.useTimeStart=e.target.value
					this.form.useTimeStart=this.useTimeStart+":00"
				}else{
					this.useTimeEnd=e.target.value
					this.form.useTimeEnd=this.useTimeEnd+":59"
				}
			},
			
			// 选择返券/门店卡余额
			couponsCardChange(e){
				this.form.couponsCard=e.detail.value	
				this.form.couponsName=''
				this.form.couponsTermType=''
				this.form.couponsTermTime=''
				this.form.upperAmount=''
				this.form.lowerAmount=''
				this.form.assistTime=''
				this.form.assistNum=''
				this.form.couponsTermType=1
				this.form.couponsTermTime=''
				this.ticketValidIndex=0
				this.form.grantType=1
				this.form.assistSuccessType=1
				// console.log(e.detail.value,"选择返券/门店卡余额：1券  2余额")
			},
			
			// 金额上/下线输入限制（只能输入正整数）
			handleInput(event){
				let type=event.currentTarget.dataset.type
				let value = event.detail.value
				
				// 第一个正则：过滤以0开头的数字 
				// 第二个正则：过滤掉所有非1-9的字符
				value=value.replace(/^0/g, '').replace(/[^0-9]/g, '')
				// value=value.replace(/^0+([0-9]+)/g, '$1');
				this.$nextTick(()=>{    
					if(type=='upperAmount'){
						this.form.upperAmount = value;
					}else if(type=='lowerAmount'){
						this.form.lowerAmount = value;
					}else if(type=='assistTime'){
						this.form.assistTime = value;
					}else if(type=='assistNum'){
						this.form.assistNum = value;
					}else if(type=='day'){
						this.form.couponsTermTime = value;
					}
				})
			},
			
			// 发放方式
			grantTypeChange(e){
				this.form.grantType=e.detail.value
			},
			
			// 随机立减券有效时间
			ticketPickerChange(e){
				this.ticketValidIndex = e.detail.value
				this.form.couponsTermType=this.ticketValidArray[this.ticketValidIndex].value
				this.form.couponsTermTime=''
				this.ticketStartTime=''
				this.ticketEndTime=''
			},
			
			ticketDateChange(e){
				let index = e.currentTarget.dataset.index
				if (index == 0) {
					this.ticketStartTime = e.target.value
				} else {
					this.ticketEndTime = e.target.value
				}
				this.form.couponsTermTime=this.ticketStartTime+ "~" + this.ticketEndTime;
			},
			
			getTicket(e){
				this.form.assistSuccessType=e.detail.value
			},
			
			// 保存
			submit(){
				this.form.storeId=uni.getStorageSync('store_id')
				this.form.tableType=this.shopIndex.toString()
				if(this.form.termType==1){  // 永久有效
					this.form.termStart=''
					this.form.termEnd=''
				}else if(this.form.useTimeType==1){  // 不限时间段
					this.form.useTimeStart=''
					this.form.useTimeEnd=''
				}else if(this.form.couponsCard==2){  // 门店卡
					this.form.couponsName=''
					this.form.couponsTermType=''
					this.form.couponsTermTime=''
				}
				if(this.form.assistTime>24){
					this.$tools.showToast('助力有效时长最多24小时');
					return;
				}else if(this.form.assistNum>5){
					this.$tools.showToast('助力好友最多5人');
					return;
				}
				
				// console.log(this.form)
				if(this.form.id){
					this.$request.post(this.$api.returnActivityUpdate, this.form, {
						isJava:true,
					}).then(res => {
						if(res.code==200){
							this.$tools.showToast('修改成功');
							setTimeout(()=>{
								uni.navigateBack()
							},1000)
						}
					})
				}else{
					this.$request.post(this.$api.returnActivityAdd, this.form, {
						isJava:true,
					}).then(res => {
						if(res.code==200){
							this.$tools.showToast('新增成功');
							setTimeout(()=>{
								uni.navigateBack()
							},1000)
						}
					})
				}
			},
			
		},
	}
</script>

<style lang="scss" scoped>
	.container{
		padding: 30upx;
		overflow: hidden; // 解除BFC问题
		.modle-title{
			font-size: 36rpx;
			font-weight: bold;
			color: #fff;
			text-align: center;
			letter-spacing: 2rpx;
			&:not(:first-child){
				margin-top: 60rpx;
			}
		}
		/deep/.modle-info-box {
			.info-item {
				font-size: 28upx;
				font-family: PingFang SC;
				font-weight: 400;
				line-height: 40upx;
				color: #FFFFFF;
				padding: 30upx 0;
				border-bottom: 1upx solid #36355E;
				position: relative;
				.small {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFFFFF;
					margin: 0 40upx;
				}
				picker{
					flex: 1;
				}
				.select-input{
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
					flex: 1;
				}
				input {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
					flex: 1;
				}
		
				.icon-more {
					border-color: #FFFFFF;
					position: absolute;
					right: 10rpx;
					pointer-events: none;
				}
		
				.placeholderclass {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #FFE577;
				}
				.radio-group{
					gap: 40rpx;
				}
			}
			.remaks-box{
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #82819B;
				line-height: 40rpx;
				margin-top: 12upx;
			}
		}
		.submit-btn{
			font-size: 32rpx;
			font-family: PingFang SC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			width: 400rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #26BCFD;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin: 70rpx auto;
		}
	}
</style>